package com.atues.thread.lock;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TestLockWithProCon {

    public static void main(String[] args) {
        TestLockWithProCon testLockWithProCon = new TestLockWithProCon();
        MyData data = new MyData();
        new Thread(() -> {
            for(int i = 0 ; i < 10 ; i++){
                    data.produce();
            }
        }, "生产者1").start();
        new Thread(()->{
            for(int i = 0 ; i < 10 ; i++){

                    data.consume();

            }
        }, "消费者1").start();
        new Thread(() -> {
            for(int i = 0 ; i < 10 ; i++){

                    data.produce();

            }
        }, "生产者2").start();
        new Thread(()->{
            for(int i = 0 ; i < 10 ; i++){
                    data.consume();
            }
        }, "消费者2").start();
    }
}


class MyData{
    //数据，用队列
    Queue<Integer> workQueue;
    int MAX_SIZE = 5;
    int num = 0;
    private final  ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();//工作队列未满
    private final Condition notEmpty = lock.newCondition();//工作队列非空条件
    public MyData(){
        workQueue = new LinkedList<>();
    }



    public void produce(){

        try {
            lock.lock();
            while(workQueue.size() == MAX_SIZE) {
                notFull.await();//相当于await
            }
            workQueue.add(num);
            System.out.println(Thread.currentThread().getName() + "生产了一个数据：" + num);
            num++;
            notEmpty.signalAll();//相当于notifyAll
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }

    }
    public void consume(){

        try{
            lock.lock();
            while(workQueue.size() == 0)notEmpty.await();;
            System.out.println(Thread.currentThread().getName() + "消费了一个数据：" + workQueue.poll());
            notFull.signalAll();//唤醒所有生产者
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }
}
